import React, { createContext, useState, useEffect, useContext } from 'react';
import authService from '../services/authService';

// 创建上下文
const AuthContext = createContext(null);

// 导出自定义Hook以便在组件中使用
export const useAuth = () => useContext(AuthContext);

// 上下文提供者组件
export const AuthProvider = ({ children }) => {
    const [currentUser, setCurrentUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    // 初始化时检查本地存储中的用户信息
    useEffect(() => {
        const initAuth = async () => {
            try {
                const user = authService.getCurrentUser();
                if (user) {
                    setCurrentUser(user);
                    // 可以在这里验证令牌有效性
                }
            } catch (err) {
                setError(err.message);
                authService.logout();
            } finally {
                setLoading(false);
            }
        };

        initAuth();
    }, []);

    // 注册
    const register = async (username, email, password) => {
        try {
            setLoading(true);
            console.log('开始注册:', { username, email });
            const response = await authService.register(username, email, password);
            console.log('注册响应:', response);
            setCurrentUser(authService.getCurrentUser());
            return response;
        } catch (err) {
            console.error('注册失败:', err);
            setError(err.message || 'Registration failed');
            throw err;
        } finally {
            setLoading(false);
        }
    };

    // 登录
    const login = async (username, password) => {
        try {
            setLoading(true);
            console.log('开始登录:', { username });
            const response = await authService.login(username, password);
            console.log('登录响应:', response);
            const user = authService.getCurrentUser();
            console.log('当前用户:', user);
            setCurrentUser(user);
            return response;
        } catch (err) {
            console.error('登录失败:', err);
            setError(err.message || 'Login failed');
            throw err;
        } finally {
            setLoading(false);
        }
    };

    // 注销
    const logout = () => {
        authService.logout();
        setCurrentUser(null);
    };

    // 刷新令牌
    const refreshUserToken = async () => {
        try {
            setLoading(true);
            const response = await authService.refreshToken();
            return response;
        } catch (err) {
            setError(err.message || 'Token refresh failed');
            throw err;
        } finally {
            setLoading(false);
        }
    };

    // 提供的上下文值
    const value = {
        currentUser,
        loading,
        error,
        register,
        login,
        logout,
        refreshUserToken,
        isAuthenticated: authService.isAuthenticated
    };

    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}; 